package com.ft.controller;


import com.ft.domain.Commodity;
import com.ft.service.CommodityService;
import com.ft.utils.Code;
import com.ft.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ft
 * @since 2022-06-01
 */
@CrossOrigin
@RestController
@RequestMapping("/commoditys")
public class CommodityController {
    @Autowired
    CommodityService commodityService;

    /**
     * 查询所有商品（state不为2的商品信息）
     * @return 返回所有商品集合
     */
    @GetMapping("")
    public Result selectAll(){
        List<Commodity> commodities = commodityService.selectAll();
        System.out.println(commodities);
        return new Result(Code.GET_OK,commodities,"查询成功");
    }

    /**
     *修改商品
     * @param commodity 传入修改的商品对象
     * @return 返回受影响的行数
     */
    @PutMapping("")
    public Result updataCommodity(@RequestBody Commodity commodity){
        commodity.setUpdateTime(String.valueOf(new Timestamp(System.currentTimeMillis())));
        System.out.println(commodity);
        int i = commodityService.updateCommodity(commodity);
        if(i == 1){
            return new Result(Code.PUT_OK,"修改成功");
        }else {
            return new Result(Code.PUT_ERR,"修改失败");
        }
    }

    /**
     * 添加商品
     * @return 返回受影响的行数结果
     */
    @PostMapping("")
    public Result addCommodity(@RequestBody Commodity commodity){
        System.out.println(commodity);
        int i = commodityService.addCommodity(commodity);
        if(i == 1){
            return new Result(Code.POST_OK,"添加成功");
        }else {
            return new Result(Code.POST_ERR,"添加失败");
        }
    }

    /**
     * 查询商品名称是否已经存在
     * @param name
     * @return
     */
    @GetMapping("/{name}")
    public Result selectByCommodityName(@PathVariable String name){
        String s = commodityService.selectByName(name);
        if(s == null){
            return new Result(Code.GET_OK, "该用户名不存在");
        }else {
            return new Result(Code.GET_ERR,"用户名已存在");
        }
    }

    /**
     * 查询已上架商品
     * @return 返回查询情况，为空查询失败，否则成功
     */
    @GetMapping("/grounding")
    public Result selectGrounding(){
        List<Commodity> commodities = commodityService.selectGrounding();
        return new Result(Code.GET_OK,commodities,"查询成功！");
    }

    /**
     * 查询以下架商品
     * @return 返回查询情况，为空查询失败，否则成功
     */
    @GetMapping("/offtheshelf")
    public Result selectOffTheShelf(){
        List<Commodity> commodities = commodityService.selectOffTheShelf();
        return new Result(Code.GET_OK,commodities,"查询成功！");
    }

    /**
     * 查询所有以逻辑删除的商品
     * @return 返回查询情况，为空查询失败，否则成功
     */
    @GetMapping("/delete")
    public Result selectByState(){
        List<Commodity> commodities = commodityService.selectByState();
        return new Result(Code.GET_OK,commodities,"查询成功！");
    }
}

